"""凭证合并功能"""

from datetime import datetime, timedelta, date

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError


class AccMove(models.Model):
    _inherit = 'account.move'

    is_combined = fields.Boolean('是否已合并', compute="_compute_is_combined", store=True)

    @api.depends('line_ids.is_combined')
    def _compute_is_combined(self):
        for move in self:
            move.is_combined = all(move.line_ids.mapped('is_combined'))

    def combine_account_moves(self, account_move_ids):
        """合并指定的account.move"""
        account_moves = self.env['account.move'].browse(account_move_ids)
        account_move_lines = account_moves.mapped('line_ids').filtered(lambda x: not x.is_combined)
        combined_account_move_id = self.env['combined.account.move.line'].combine_account_move_line(account_move_lines)
        return self.view_combined_moves_action(combined_account_move_id)

    def view_combined_moves_action(self, combine_account_moves):
        """返回动作字典"""
        # action = self.env.ref('nd_combine_account_move.combined_move_action').read()[0]
        action = {
            'name': '合并的凭证',
            'type': 'ir.actions.act_window',
            'res_model': 'combined.account.move',
            'views': [(False, 'tree'), (False, 'form')],
        }
        if len(combine_account_moves) < 1:
            raise UserError('没有合并的凭证！')
        elif len(combine_account_moves) == 1:
            action['res_id'] = combine_account_moves.id
            action['views'] = [[False, 'form']]
        else:
            action['domain'] = [('id', 'in', combine_account_moves.ids)]
        return action


class AccMoveLine(models.Model):
    _inherit = 'account.move.line'

    is_combined = fields.Boolean('是否已合并', compute="_compute_is_combined", store=True)
    combined_move_lines = fields.One2many('combined.account.move.line', 'origin_move_line_id', string="合并后的凭证明细")

    @api.depends('combined_move_lines', 'combined_move_lines.move_id.state')
    def _compute_is_combined(self):
        """如果有非取消状态的合并凭证记录，就认为是已合并的。"""
        for order in self:
            order.is_combined = bool(order.combined_move_lines.filtered(lambda x: x.move_id.state != 'cancel'))

    def combine_account_move_lines(self, account_move_line_ids):
        """合并指定的account.move.line"""
        account_move_lines = self.env['account.move.line'].browse(account_move_line_ids)
        combined_account_move_id = self.env['combined.account.move.line'].combine_account_move_line(account_move_lines)
        return self.env['account.move'].view_combined_moves_action(combined_account_move_id)

